﻿using System;
using System.Collections.Generic;
using System.Data.EntityClient;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace StarfleetCommanderSecure
{
    class SqlConnectionStringManager
    {
        private static string _connectionString;
        internal static string EfConnectionString { get; private set; }
        internal static void SetConnectionString(string connectionString, string efConnectionString)
        {
            _connectionString = connectionString;
            EfConnectionString = efConnectionString;
        }
        internal static string ConnectionString
        {
            get
            {
                if (_connectionString.IsNullOrEmpty())
                {
                    _connectionString = FindConnectionString();
                }
                return _connectionString;
            }
            set { _connectionString = value; }
        }

        private static string FindConnectionString()
        {
            var connectionStrings = System.Configuration.ConfigurationManager.ConnectionStrings;
            
            if (_connectionString.IsNullOrEmpty())
                using (var cnSql = new System.Data.SqlClient.SqlConnection())
                {
                    for (int i = 0; i < connectionStrings.Count; i++)
                    {
                        if (connectionStrings[i].ConnectionString.Contains("metadata="))
                        {
                            var ecsb = new EntityConnectionStringBuilder(connectionStrings[i].ConnectionString);
                            cnSql.ConnectionString = ecsb.ProviderConnectionString;
                        }
                        else
                            cnSql.ConnectionString = connectionStrings[i].ConnectionString;
                        try
                        {
                            cnSql.Open();
                            cnSql.Close();
                            
                            return connectionStrings[i].ConnectionString;
                        }
                        catch (System.Data.SqlClient.SqlException sqlEx)
                        {
                            Trace.WriteLine("Connection failed:" + sqlEx.ToString());
                        }


                    }
                }
            throw new ApplicationException("Could not find a valid connection string");

        }

    }
}
